package com.haojiang.mh.remote.ui.activity;

import android.content.Context
import android.graphics.Color
import android.os.Build
import android.text.TextUtils
import android.view.View
import android.view.WindowManager
import android.widget.ImageView
import android.widget.LinearLayout
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.haojiang.mh.AppContext
import com.haojiang.mh.R
import com.haojiang.mh.remote.base.BaseActivity
import com.haojiang.mh.remote.bean.ConnectKey
import com.haojiang.mh.remote.callback.IGroupInfo
import com.haojiang.mh.remote.enums.EConnect
import com.haojiang.mh.remote.event.AddGroupEvent
import com.haojiang.mh.remote.ui.frag.FragFirst
import com.haojiang.mh.remote.ui.frag.FragSecond
import com.haojiang.mh.remote.ui.frag.FragThird
import com.haojiang.mh.remote.utils.BleUtil.Companion.addGroupKey
import com.haojiang.mh.remote.utils.BleUtil.Companion.addGroupValueList
import com.haojiang.mh.remote.utils.BleUtil.Companion.groupData
import com.haojiang.mh.remote.utils.BleUtil.Companion.saveGroupInterfaceNo
import com.haojiang.mh.remote.utils.Util.Companion.hideInputKeyboard
import kotlinx.android.synthetic.main.activity_guide.*
import org.greenrobot.eventbus.EventBus

class GuideActivity : BaseActivity() {


    private var lastPos = 0
    private val fragList: ArrayList<Fragment> = arrayListOf(
        FragFirst(),
        FragSecond(),
        FragThird()
    )

    private val guideFragStateAdapter = GuideFragStateAdapter(this)
    private val onPageChangeCallback = object : ViewPager2.OnPageChangeCallback() {
        override fun onPageSelected(position: Int) {
            llDots.getChildAt(lastPos).setEnabled(false)
            llDots.getChildAt(position).setEnabled(true)
            //把上一个高亮设置为灰色

            //把上一个高亮设置为灰色
            lastPos = position
            setBtnPosStatus(lastPos)
            when (position) {
                0 -> {
                    tvTitle.setText(AppContext.instance().getString(R.string.f_select_control_mode))
                }
                1 -> {
                    tvTitle.setText(AppContext.instance().getString(R.string.f_select_bed_type))
                    hideInputKeyboard(this@GuideActivity)
                }
                2 -> {
                    tvTitle.setText(AppContext.instance().getString(R.string.f_select_device))
                    hideInputKeyboard(this@GuideActivity)
                    val frag = fragList.get(fragList.size - 1)
                    if (frag is IGroupInfo) {
                        val iGroupInfo = frag as IGroupInfo
                        iGroupInfo.onSelectDevice()
                    }
                }
            }
        }
    }

    private val onClickListener = object : View.OnClickListener {
        override fun onClick(v: View?) {
            v?.let {
                when (v.id) {
                    R.id.ivBack -> {
                        if (lastPos != 0) {
                            viewPager2.setCurrentItem(lastPos - 1, true)
                        } else {
                            finish()
                        }
                    }

                    R.id.ivNext -> {
                        if (lastPos != fragList.size - 1) {
                            viewPager2.setCurrentItem(lastPos + 1, true)
                        } else {

                        }
                    }

                    R.id.btnFinish -> {
                        //获取选择的列表
                        val frag = fragList.get(fragList.size - 1)
                        if (frag is IGroupInfo) {
                            val iGroupInfo = frag as IGroupInfo
                            iGroupInfo.onSelectDeviceFinish()
                        }

                        if (TextUtils.isEmpty(groupData.groupKey.name)) {
                            viewPager2.setCurrentItem(0, true)
                            showToast(AppContext.instance().getString(R.string.m_name_your_bed))
                        } else if (groupData.groupValueList.size <= 0) {
                            showToast(AppContext.instance().getString(R.string.m_selection_can_not_be_empty))
                        } else {
//                            LogUtil.e("我的数据=" + groupData.toString())
                            val groupId = addGroupKey(this@GuideActivity, groupData.groupKey.name, groupData.groupKey.type)
                            addGroupValueList(this@GuideActivity, groupId, groupData.groupValueList)
                            saveGroupInterfaceNo(groupId, groupData.groupKey.interfaceNo)
                            EventBus.getDefault().post(AddGroupEvent())
                            finish()
                        }

                    }
                    else -> {
                    }
                }
            }
        }
    }


    override fun getLayoutId(): Int {
        return R.layout.activity_guide
    }

    override fun initListener() {
        //添加点
        addDots()
        setBtnPosStatus(lastPos)

        viewPager2.offscreenPageLimit = fragList.size
        viewPager2.adapter = guideFragStateAdapter
        viewPager2.registerOnPageChangeCallback(onPageChangeCallback)
        guideFragStateAdapter.setData(fragList)

        ivBack.setOnClickListener(onClickListener)
        ivNext.setOnClickListener(onClickListener)
        btnFinish.setOnClickListener(onClickListener)

        val groupId = System.currentTimeMillis()
        groupData.groupKey = ConnectKey(
            groupId,
            EConnect.CONNECT_GROUP_SINGLE.data
        )
    }

    private fun setBtnPosStatus(curPos: Int) {
        when (curPos) {
            0 -> {
                ivNext.visibility = View.VISIBLE
                btnFinish.visibility = View.INVISIBLE
            }
            fragList.size - 1 -> {
                ivNext.visibility = View.INVISIBLE
                btnFinish.visibility = View.VISIBLE
            }
            else -> {
                ivNext.visibility = View.VISIBLE
                btnFinish.visibility = View.INVISIBLE
            }
        }
    }

    private fun addDots() {
        for (i in fragList.indices) {
            val point = ImageView(this)
            point.setBackgroundResource(R.drawable.sel_point)
            llDots.addView(point)
            val params: LinearLayout.LayoutParams = LinearLayout.LayoutParams(
                dpToPx(this, 10f),
                dpToPx(this, 10f)
            )
            if (i == 0) {
                point.isEnabled = true
            } else if (i == fragList.size) {
            } else {
                point.isEnabled = false
                params.leftMargin = dpToPx(this, 10f)
            }
            point.setLayoutParams(params)
        }
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    fun dpToPx(context: Context, dpValue: Float): Int {
        val scale = context.resources.displayMetrics.density
        return (dpValue * scale + 0.5f).toInt()
    }

    /**
     * 让状态栏变透明
     */
    private fun changeStatusBarColor() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            val window = window
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
            window.statusBarColor = Color.TRANSPARENT
            window.decorView.systemUiVisibility =
                View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
        }
    }

    class GuideFragStateAdapter(fm: FragmentActivity) : FragmentStateAdapter(fm) {

        val fragList: ArrayList<Fragment> = arrayListOf()

        fun setData(fragList: ArrayList<Fragment>) {
            this.fragList.clear()
            this.fragList.addAll(fragList)
            notifyDataSetChanged()
        }

        override fun createFragment(position: Int): Fragment {
            return fragList.get(position)
        }

        override fun getItemCount(): Int {
            return fragList.size
        }


        override fun containsItem(itemId: Long): Boolean {
            return super.containsItem(itemId)
        }

    }

}